package cn.yj.lock;

import cn.yj.lock.aqs.AppSync;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 永健
 * @since 2022-02-24 17:32
 */
public class APPLock implements ILock {

    private static final int LOCK_STATE = 1;

    /**
     * 同一个Key维护同一把锁
     */
    private static final Map<String, AppSync> LOCK_MAP = new ConcurrentHashMap<>();

    private volatile AppSync appSync;

    public APPLock() {
        appSync =new AppSync();
    }

    /**
     * 加锁
     *
     * @param key
     */
    @Override
    public void lock(String key) {
//        checkKeyNull(key);
//        AppSync appSync = LOCK_MAP.computeIfAbsent(key, lock -> new AppSync());
//        appSync.increment();
        appSync.acquire(LOCK_STATE);
    }

    /**
     * 释放锁资源
     *
     * @param key
     */
    @Override
    public void unlock(String key) {
        checkKeyNull(key);
//        AppSync appSync = LOCK_MAP.get(key);
//        if (appSync != null) {
//            appSync.release(LOCK_STATE);
//            if (appSync.decrementAndGet() == 0) {
//                LOCK_MAP.remove(key);
//            }
//            System.out.println(appSync.getCount());
//            return;
//        }
        appSync.release(LOCK_STATE);
    }

    /**
     * k非空校验
     *
     * @param key
     */
    private void checkKeyNull(String key) {
        if (key == null || "".equals(key)) {
            throw new RuntimeException("锁条件异常");
        }
    }

}
